import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/api'; 
import { MdlSnackbarService, MdlDialogService } from '@angular-mdl/core';
import { CustomService } from '../../custom.service';
@Component({
    templateUrl: './biz-add.component.html',
    styleUrls: ['./biz-add.component.scss'],
    providers: [CustomService]
})
export class BizAddComponent implements OnInit {
    bizs: any[] = [];
    selectedBiz: any = {};
    bizItemForm: FormGroup;
    bizItem: any = {};
    constructor(
        private fb: FormBuilder,
        private dialogService: MdlDialogService,
        public ref: DynamicDialogRef,
        public config: DynamicDialogConfig,
        private customService: CustomService) {
    }

    ngOnInit() {
        this.buildForm();
        this.customService.loadCustomBiz().subscribe(data => this.bizs = data);
    }
    /**新增 */
    save() {
        let value = this.bizItemForm.value;
        if (this.selectedBiz) {
            value.bizId = this.selectedBiz.value;
            value.bizName = this.selectedBiz.label;
        } else {
            value.bizName = value.bizId;
            value.bizId = '';
        }
        if (!value.bizName) {
            this.dialogService.alert('请填写或选择业务名称');
            return;
        }
        if (!value.itemName) {
            this.dialogService.alert('请填写栏目名称');
            return;
        }
        this.customService.createCustomBiz(value).subscribe(data => {
            this.ref.close(data);
        });
    }

    /**取消关闭窗口 */
    cancel() {
        this.ref.close();
    }

    buildForm(): void {
        this.bizItemForm = this.fb.group({
            'bizId': [this.bizItem.bizId],
            'itemName': [this.bizItem.itemName]
        });
    }


    bizChange($event: any) {
        this.selectedBiz = null;
        this.bizs.forEach(data => {
            if (data.label == $event.value || data.value == $event.value) {
                this.selectedBiz = data;
            }
        });
    }
}
